package com.fingard.dsp.bank.directbank.epay02;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;

public class EPAY02SinglePay extends EPAY02Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
            if (actItem == null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号" + p_req1908.singleDetail.recAct + "对应的商户配置信息";
                tmpRetDetail.transAmt = p_req1908.singleDetail.payAmount;
                tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;

                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            JSONObject bizContent = new JSONObject();
            bizContent.put("institutionCode", bankFront.org);//机构号
            bizContent.put("merchantCode", actItem.merchantId);//商户编码
            /**
             * memo字段内容：通过分隔符|_|拼接
             * [0]productCode 产品编码
             * [1]payParty 赔付方
             * [2]phoneNo 投保人手机号
             * [3]occurrenceTime 出险时间 "yyyy-MM-dd HH:mm:ss"
             * [4]occurrencePlace 出险地点
             * [5]PolicyNo 保单号
             * [6]claimNo 赔案号
             */
            String[] memo = p_req1908.singleDetail.memo.split("\\|_\\|");
            if (memo.length >= 7) {
                bizContent.put("productCode", memo[0]);//产品编码
                bizContent.put("payParty", memo[1]);//赔付方
                bizContent.put("phoneNo", memo[2]);//投保人手机号
                bizContent.put("occurrenceTime", memo[3]);//出险时间
                bizContent.put("occurrencePlace", memo[4]);//出险地点
                bizContent.put("policyNo", memo[5]);//保单号
                bizContent.put("claimNo", memo[6]);//赔案号(理赔请求流水号)
            } else {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "MEMO字段的长度不够，请检查字段值！";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            bizContent.put("orderNo", p_req1908.singleDetail.attribute13);//订单号
            bizContent.put("claimApplyTime", Format.DateTimeFormat.format(p_req1908.singleDetail.getPayDateOnly()));//理赔申请时间
            bizContent.put("bestPayAccount", p_req1908.singleDetail.recAct);//翼支付帐号
            bizContent.put("contactUserName", p_req1908.singleDetail.payName);//联系人姓名
            bizContent.put("contactUserPhone", getBankConfig().getValueAsString("contactUserPhone"));//联系人手机号
            bizContent.put("claimApplyAmount", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount));//理赔金额(单位：分)
            String content = convertMapToSortStr(bizContent);
            WriteBankLogLn("待签名数据：" + content);
            String signature = sign(content, "SHA256withRSA", actItem);
            bizContent.put("sign", signature);
            String tmpReqMsg = bizContent.toJSONString();
            WriteBankLogStep2(tmpReqMsg);
            String[] tmpStrRet = sendToBank(tmpReqMsg, bankFront.getUrl("singlePay"));

            if (tmpStrRet[0].length() == 0) {
                WriteBankLogStep3(tmpStrRet[1]);
                JSONObject resultObj = JSONObject.parseObject(tmpStrRet[1]);
                String responseCode = resultObj.getString("success");
                if ("true".equals(responseCode)) {
                    JSONObject result = resultObj.getJSONObject("result");
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = resultObj.getString("errorMsg");
                    tmpRetDetail.transState = PaymentState.SUCCESS;
                    tmpRetDetail.payInfoCode = resultObj.getString("errorCode");
                    tmpRetDetail.outTransID = result.getString("claimRequestNo");
                } else {
                    tmpRetDetail.transState = PaymentState.FAIL_Payment;
                    tmpRetDetail.respCode = resultObj.getString("errorCode");
                    tmpRetDetail.respInfo = resultObj.getString("errorMsg");
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[0];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        tmpRetDetail.reqSeqID = p_req1944.askNumber;

        try {
            String localFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + p_req1944.askNumber + ".txt";
            WriteBankLogLn("本机交易通知结果文件路径:" + localFilePath);
            File tmpLocalFile = new File(localFilePath);
            if (tmpLocalFile.exists()) {
                String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
                WriteBankLogLn("本机通知结果文件内容:\r\n" + tmpStrRet);

                JSONArray tmpRespArray = JSONArray.parseArray(tmpStrRet);
                JSONObject tmpRespJson = tmpRespArray.getJSONObject(0);

                tmpRetDetail.respCode = "0";
                String tmpRespInfo = tmpRespJson.getString("errorMessage");
                if (StringHelper.hasAnyChar(tmpRespInfo)) {
                    tmpRetDetail.respInfo = tmpRespInfo;
                }
                tmpRetDetail.transState = tmpRespJson.getString("tradeState");
                tmpRetDetail.payInfoCode = tmpRespJson.getString("errorCode");
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "本机通知结果文件不存在,请稍后查询!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}